using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using ECommerce.Library.Web;
using AutoGear.BLL;
using System.Collections.Generic;
using ECommerce.Library.DataStructure;
using ECommerce.Library;

public partial class myaccount_shopping_list : SitePublicBasePage
{
    protected void Page_Load(object sender, EventArgs e)
    {

        if (!Page.IsPostBack)
        {
            if (SessionManager.IsUserLoggedIn)
            {
                SetPageTitleAndBreadcramb();
                LoadData();
            }
            else
            {
                Response.Redirect(string.IsNullOrEmpty(SupplierId) ? CustomSiteMap.Login : "~/partner/" + SupplierId + "/login.aspx");
            }
        }
        uccResponseMessage.Visible = false;
    }

    private void SetPageTitleAndBreadcramb()
    {
        ContentPlaceHolder ph = (ContentPlaceHolder)this.Master.Master.FindControl("cphMiddleContent");

        Literal litPageTitle = (Literal)ph.FindControl("litPageTitle");
        Literal litCurrentPage = (Literal)ph.FindControl("litCurrentPage");

        if (litPageTitle != null)
        {
            litCurrentPage.Text = litPageTitle.Text = "Shopping List";

        }
    }

    protected void LoadData()
    {
        int userId = SessionManager.IsUserLoggedIn ? SessionManager.LoggedUser.UserId : 0;
        if (userId > 0)
        {
            ReadWriteCustomCollection<Favorites> favorites = Favorites.GetFavoritesByUserId(userId);
            if (favorites.Count > 0)
            {
                rptFavorites.DataSource = favorites;
                rptFavorites.DataBind();
                pnlShoppingList.Visible = true;
                pnlEmptyList.Visible = false;
            }
            else
            {
                pnlShoppingList.Visible = false;
                pnlEmptyList.Visible = true;
            }
        }
    }



    protected void btnItemRemove_Click(object sender, EventArgs e)
    {
        try
        {
            int userId = SessionManager.IsUserLoggedIn ? SessionManager.LoggedUser.UserId : 0;

            ReadWriteCustomCollection<Favorites> favorites = new ReadWriteCustomCollection<Favorites>();
            foreach (RepeaterItem row in rptFavorites.Items)
            {
                if (row.ItemType == ListItemType.Item || row.ItemType == ListItemType.AlternatingItem)
                {
                    CheckBox cbxSelect = (CheckBox)row.FindControl("cbxSelect");
                    if (cbxSelect != null && cbxSelect.Checked)
                    {
                        HiddenField hdfFavoriteId = (HiddenField)row.FindControl("hdfFavoriteId");
                        int favoriteId;
                        if (int.TryParse(hdfFavoriteId.Value, out favoriteId))
                        {
                            favorites.Add(Favorites.Load(favoriteId));
                        }
                    }
                }
            }
            Favorites.DeleteFavorites(favorites);
            LoadData();
        }
        catch (Exception ex)
        {
            uccResponseMessage.SetFailMessage(AutoGearCommonMessage.CommonFailure);
            uccResponseMessage.Visible = true;
        }
    }

    protected void Add_To_Cart(object sender, CommandEventArgs e)
    {
        try
        {
            if (e.CommandName == "AddToCart")
            {
                int rowIndex;
                if (int.TryParse(e.CommandArgument.ToString(), out rowIndex))
                {
                    RepeaterItem rptRow = rptFavorites.Items[rowIndex];
                    if (rptRow != null)
                    {
                        int qty, favoriteId;
                        TextBox tbxQuantity = (TextBox)rptRow.FindControl("tbxQuantity");
                        HiddenField hdfFavoriteId = (HiddenField)rptRow.FindControl("hdfFavoriteId");
                        Label lblQuantityRequired = (Label)rptRow.FindControl("lblQuantityRequired");

                        Label lblMetalType = (Label)rptRow.FindControl("lblMetalType");

                        if (tbxQuantity != null && hdfFavoriteId != null)
                        {
                            int.TryParse(tbxQuantity.Text.ToString().Trim(), out qty);
                            int.TryParse(hdfFavoriteId.Value.ToString(), out favoriteId);
                            Favorites favorite = Favorites.Load(favoriteId);
                            Product product = Product.Load(favorite.Product.ProductId);
                            if (qty > 0)
                            {
                                this.AddCartItemToShoppingCart(qty, product, lblMetalType.Text.ToString(), "N");
                                uccResponseMessage.SetSuccessMessage(AutoGearCommonMessage.ShippingListAddToCartSuccessful);
                                uccResponseMessage.Visible = true;

                            }
                            else
                            {

                                lblQuantityRequired.Text = "*";
                                uccResponseMessage.SetFailMessage(AutoGearCommonMessage.ShippingListInvalidQuantity);
                                uccResponseMessage.Visible = true;
                            }
                        }

                    }
                }
            }
        }
        catch (Exception ex)
        {
            uccResponseMessage.SetFailMessage(AutoGearCommonMessage.ShippingListAddToCartFailed);
            uccResponseMessage.Visible = true;
        }

    }

    protected void btnCartAddAll_Click(object sender, EventArgs e)
    {
        try
        {
            bool hasError = false;
            foreach (RepeaterItem rptRow in rptFavorites.Items)
            {
                if (rptRow.ItemType == ListItemType.Item || rptRow.ItemType == ListItemType.AlternatingItem)
                {
                    CheckBox cbxSelect = (CheckBox)rptRow.FindControl("cbxSelect");
                    Label lblQuantityRequired = (Label)rptRow.FindControl("lblQuantityRequired");
                    lblQuantityRequired.Text = "&nbsp;";
                    if (cbxSelect != null && cbxSelect.Checked)
                    {
                        int qty, favoriteId;
                        TextBox tbxQuantity = (TextBox)rptRow.FindControl("tbxQuantity");
                        HiddenField hdfFavoriteId = (HiddenField)rptRow.FindControl("hdfFavoriteId");

                        if (tbxQuantity != null && hdfFavoriteId != null)
                        {
                            int.TryParse(tbxQuantity.Text.ToString().Trim(), out qty);
                            int.TryParse(hdfFavoriteId.Value.ToString(), out favoriteId);
                            Favorites favorite = Favorites.Load(favoriteId);
                            Product product = Product.Load(favorite.Product.ProductId);
                            if (qty == 0 || qty < product.Stocks[0].PkgQuanity)
                            {
                                lblQuantityRequired.Text = "*";
                                hasError = true;
                                uccResponseMessage.SetFailMessage(AutoGearCommonMessage.ShippingListInvalidQuantity);
                                uccResponseMessage.Visible = true;
                            }
                        }
                    }
                }
            }

            if (!hasError)
            {
                foreach (RepeaterItem rptRow in rptFavorites.Items)
                {
                    if (rptRow.ItemType == ListItemType.Item || rptRow.ItemType == ListItemType.AlternatingItem)
                    {
                        CheckBox cbxSelect = (CheckBox)rptRow.FindControl("cbxSelect");
                        if (cbxSelect != null && cbxSelect.Checked)
                        {
                            int qty, favoriteId;
                            TextBox tbxQuantity = (TextBox)rptRow.FindControl("tbxQuantity");
                            HiddenField hdfFavoriteId = (HiddenField)rptRow.FindControl("hdfFavoriteId");
                            Label lblMetalType = (Label)rptRow.FindControl("lblMetalType");

                            if (tbxQuantity != null && hdfFavoriteId != null)
                            {
                                int.TryParse(tbxQuantity.Text.ToString().Trim(), out qty);
                                int.TryParse(hdfFavoriteId.Value.ToString(), out favoriteId);
                                Favorites favorite = Favorites.Load(favoriteId);
                                Product product = Product.Load(favorite.Product.ProductId);
                                if (qty > 0)
                                {
                                    if (qty >= product.Stocks[0].PkgQuanity && qty % product.Stocks[0].PkgQuanity == 0)
                                    {
                                        this.AddCartItemToShoppingCart(qty, product, lblMetalType.Text.ToString(), "N");
                                        uccResponseMessage.SetSuccessMessage(AutoGearCommonMessage.ShippingListAddToCartSuccessful);
                                        uccResponseMessage.Visible = true;
                                    }
                                    else
                                    {
                                        uccResponseMessage.SetFailMessage("Invalid Package quantity");
                                        uccResponseMessage.Visible = true;
                                    }

                                }


                            }
                        }
                    }
                }
            }
        }
        catch (Exception ex)
        {
            uccResponseMessage.SetFailMessage(AutoGearCommonMessage.CommonFailure);
            uccResponseMessage.Visible = true;
        }
    }

    protected void AddCartItemToShoppingCart(int qty, Product product, string MetalType, string GiftWrapper)
    {
        ShoppingCart shoppingcart = AutoGearSessionManager.ShoppingCart;
        CartItem cartItem = new CartItem(product, qty, MetalType, GiftWrapper);
        shoppingcart.AddCartItem(cartItem);
        AutoGearSessionManager.ShoppingCart = shoppingcart;
    }


    protected void rptFavorites_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Header)
        {
            CheckBox cbxSelectAll = (CheckBox)e.Item.FindControl("cbxSelectAll");
            cbxSelectAll.Attributes.Add("onclick", "javascript:SelectAll('" + rptFavorites.ClientID + "','" + cbxSelectAll.ClientID + "','cbxSelect')");
        }
        else if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
        {
            Favorites favorite = (Favorites)e.Item.DataItem;
            Button btnCartAdd = (Button)e.Item.FindControl("btnCartAdd");
            btnCartAdd.CommandArgument = e.Item.ItemIndex.ToString();

            Image imgItemImage = (Image)e.Item.FindControl("imgItemImage");
            imgItemImage.ImageUrl = ImageResizer.CheckImageMissing(favorite.Product.ProductImageSmallThumbnail, AutoGear.BLL.SiteSettings.NoImageSmallThumbnailUrl);

            TextBox tbxQuantity = (TextBox)e.Item.FindControl("tbxQuantity");
            tbxQuantity.MaxLength = SiteUtility.MaximumQuantityLength;
            Product product = Product.Load(favorite.Product.ProductId);
            tbxQuantity.Text = product.Stocks[0].PkgQuanity.ToString();
        }
    }

}
